package com.topdt.jbpm.web.servlet.action;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.thx.common.spring.BeanFactory;
import com.thx.common.util.ThreadLocalContext;
import com.thx.common.web.ActionResult;
import com.topdt.jbpm.Constants;
import com.topdt.jbpm.identity.User;
import com.topdt.jbpm.model.Todo;
import com.topdt.jbpm.model.WorkOpinion;
import com.topdt.jbpm.service.CommentService;
import com.topdt.jbpm.service.TodoService;
import com.topdt.jbpm.web.servlet.JbpmServlet;

/**
 *
 * 建立日期 : 2013-7-13 上午10:44:15<br>
 * 作者 : 武海峰<br>
 * 模块 : <br>
 * 描述 : <br>
 * 修改历史: 序号 日期 修改人 修改原因 <br>
 * 1 <br>
 * 2 <br>
 */
public class OptionAction extends JbpmBaseAction {

	public OptionAction(JbpmServlet servlet) {
		super(servlet);
	}

	public void save(HttpServletRequest request, HttpServletResponse response) {
		String workId = request.getParameter("workId");
		String activity = request.getParameter("activity");
		String opnContent = request.getParameter("opinion");
		// 1、先判断有没有操作意见的权限
		User user = (User) ThreadLocalContext.get(Constants.USER_KEY);
		String userId = user.getId();

		TodoService todoService = (TodoService) BeanFactory.getBean("todoService");
		Todo todo = todoService.findTodoByWorkIdAndActivity(userId, workId, activity);
		ActionResult result = new ActionResult(ActionResult.FAIL, "服务端异常", null);
		;
		if (todo != null) {
			CommentService cmtService = (CommentService) BeanFactory.getBean("commentService");
			WorkOpinion opn = cmtService.getWorkOPioionsByTodoIdPid(todo.getTodoId(), userId);
			if (opn == null) {
				opn = new WorkOpinion();
				opn.setActivityName(activity);
				opn.setCompanyId(todo.getCompanyId());
				opn.setSigerId(userId);
				opn.setSigerName(user.getName());
				opn.setSignTime(new Date());
				opn.setWorkId(workId);
				opn.setOpinionContent(opnContent);
				opn.setTodoId(todo.getTodoId());
				cmtService.saveorUpdate(opn);
			} else {
				cmtService.update(opn.getOpinionId(), opnContent);
				opn.setOpinionContent(opnContent);
			}
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("opinion", opn);
			result = new ActionResult(ActionResult.SUCCESS, "保存成功", data);
		} else {
			// 没有权限操作
			result = new ActionResult(ActionResult.FAIL, "没有权限", null);
		}
		this.responseJson(response, result);
	}

	// 查询某个环节的意见
	public void actOption(HttpServletRequest request, HttpServletResponse response) {
		String workId = request.getParameter("workId");
		String activity = request.getParameter("activity");
		CommentService commentService = (CommentService) BeanFactory.getBean("commentService");
		List<Object[]> list = commentService.getWorkOptionByWorkIdAndActivity(workId, activity);
		responseJson(response, list);
	}
}